﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pixeldyne.Core.Extensions
{
	public static class Lists
	{
		/// <summary>
		/// Removes the last element.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="list">The list.</param>
		public static void RemoveLast<T>(this IList<T> list)
		{
			list.RemoveAt(list.Count - 1);
		}

		/// <summary>
		/// Removes the first element.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="list">The list.</param>
		public static void RemoveFirst<T>(this IList<T> list)
		{
			list.RemoveAt(0);
		}

		#region Average
		public static double Avg(this IEnumerable<int> list)
		{
			int sum = 0, count = 0;

			foreach (int item in list)
			{
				sum += item;
				count++;
			}

			return (double)sum / count;
		}
		#endregion

		#region Median

		private static double GetMedian<T>(T[] array) where T : struct
		{
			var sortedArray = (double[])array.Clone();
			array.CopyTo(sortedArray, 0);

			Array.Sort(sortedArray);

			int median = sortedArray.Length / 2;

			return (sortedArray.Length % 2 != 0) ? sortedArray[median] : ((sortedArray[median] + sortedArray[median - 1]) / 2);
		}

		public static double Median(this int[] array)
		{
			return GetMedian(array);
		}

		public static double Median(this IEnumerable<int> array)
		{
			return GetMedian(array.ToArray());
		}

		public static double Median(this long[] array)
		{
			return GetMedian(array);
		}

		public static double Median(this double[] array)
		{
			return GetMedian(array);
		}

		public static double Median(this float[] array)
		{
			return GetMedian(array);
		}

		public static double Median(this short[] array)
		{
			return GetMedian(array);
		}

		public static double Median(this byte[] array)
		{
			return GetMedian(array);
		}
		#endregion
	}
}
